package com.example.newsapp.activity;

import static com.example.newsapp.constant.NetConstant.BASE_URL;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.newsapp.R;
import com.example.newsapp.model.Result;
import com.example.newsapp.model.User;
import com.example.newsapp.model.request.ResetPasswordRequest;
import com.example.newsapp.model.resultData.UserLoginResultData;
import com.example.newsapp.utils.HttpUtil;
import com.example.newsapp.utils.UserSessionUtil;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;

public class ResetPasswordActivity extends AppCompatActivity {
    private EditText oldPasswordEditText;
    private EditText newPasswordEditText;
    private EditText confirmPasswordEditText;
    private Button resetPasswordButton;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_password);

        initViews();

        // 设置返回按钮
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("重置密码");
        }

        // 设置重置密码按钮点击事件
        resetPasswordButton.setOnClickListener(v -> resetPassword());
    }

    private void initViews() {
        findViewById(R.id.btnBack).setOnClickListener(v -> finish());
        oldPasswordEditText = findViewById(R.id.oldPasswordEditText);
        newPasswordEditText = findViewById(R.id.newPasswordEditText);
        confirmPasswordEditText = findViewById(R.id.confirmPasswordEditText);
        resetPasswordButton = findViewById(R.id.resetPasswordButton);
    }

    private void resetPassword() {
        int userId = UserSessionUtil.getUserId(this);
        if(userId == -1){
            Toast.makeText(this, "用户未登录，请先登录后再重试", Toast.LENGTH_SHORT).show();
            return;
        }

        String oldPassword = oldPasswordEditText.getText().toString();
        String newPassword = newPasswordEditText.getText().toString();
        String confirmPassword = confirmPasswordEditText.getText().toString();

        if (oldPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }


        if (!newPassword.equals(confirmPassword)) {
            Toast.makeText(this, "两次输入的新密码不一致", Toast.LENGTH_SHORT).show();
            return;
        }

        resetPasswordButton.setEnabled(false);
        requestReset(new ResetPasswordRequest(oldPassword,newPassword));
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    private void requestReset(ResetPasswordRequest resetPasswordRequest) {
        String requestUrl = BASE_URL + "/users/reset";
        Type resultType = new TypeToken<Result<String>>() {
        }.getType();

        HttpUtil.request(ResetPasswordActivity.this,requestUrl, "PUT", resetPasswordRequest, resultType, new HttpUtil.Callback<Result<String>>() {
            @Override
            public void onSuccess(Result<String> result) {
                handleResetResponse(result);
            }

            @Override
            public void onFailure(Exception e) {
                showToast("网络异常：" + e.getMessage());
                resetPasswordButton.setEnabled(true);
            }
        });
    }

    private void handleResetResponse(Result<String> result) {
        if (result == null) {
            showToast("服务器响应异常");
            resetPasswordButton.setEnabled(true);

            return;
        }

        if (result.getCode() == 1 && result.getData() != null) {
            Toast.makeText(this, result.getData(), Toast.LENGTH_SHORT).show();
            finish();
        } else {
            String errorMsg = result.getMsg();
            if (errorMsg == null || errorMsg.isEmpty()) {
                errorMsg = "未知错误";
            }
            showToast("重置失败：" + errorMsg);
        }
        resetPasswordButton.setEnabled(true);
    }

    private void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

}